package com.share.ai.alibaba.starter.config;

import com.alibaba.cloud.ai.dashscope.agent.DashScopeAgent;
import com.alibaba.cloud.ai.dashscope.api.DashScopeAgentApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.share.ai.alibaba.starter.tools.WeatherTool;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class AiConfig {
    //langchain4j是用{{}},springboot中是{}
    //chatClient.prompt().system(s->s.param("voice",voice)) 会把参数塞到里面去
    private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手，请根据用户提问回答,以{voice}的语气回答";

    //使用jvm内存的方式---就是这么点配置
    @Bean
    public ChatMemory chatMemory() {
        InMemoryChatMemory chatMemory = new InMemoryChatMemory();
        return chatMemory;
    }

    //向量存储对象
    @Bean
    public VectorStore vectorStore(@Qualifier("dashscopeEmbeddingModel") EmbeddingModel embeddingModel) {
        SimpleVectorStore store = SimpleVectorStore.builder(embeddingModel).build();
        return store;
    }

    //List<ToolCallbackProvider> mcpTools mcp服务会初始化到这里
    @Bean
    public ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory, WeatherTool tool, List<ToolCallbackProvider> mcpTools) {
        ChatClient build = builder.defaultAdvisors()
                .defaultSystem(DEFAULT_PROMPT) //预设角色
                .defaultAdvisors(new SimpleLoggerAdvisor())// 实现 Logger 的 Advisor
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build()) //实现记忆聊天记录
                .defaultOptions(DashScopeChatOptions.builder().withTopP(0.7).build())
                .defaultFunctions("nameFunction") //functioncall
                .defaultTools(tool, mcpTools) //functioncall的升级版本
                .build();
        return build;
    }

    //DashScopeAgent 需要自己初始化
    @Bean
    public DashScopeAgent dashScopeAgent(DashScopeAgentApi dashScopeAgentApi) {
        DashScopeAgent dashScopeAgent = new DashScopeAgent(dashScopeAgentApi);
        return dashScopeAgent;
    }
}
